<?php defined('SYSPATH') OR die('No direct access allowed.');

class Admin_Controller extends WB_Controller {

	function __construct()
	{
		$db_init = array(
			//'table'			=> '',
			//'primary_key'		=> 'id',
			'show_columns' 	=> array(
	            'username',
	            'last_login',
	            'logins',
				'password',
				'roles'
            ),
			'addable'			=> TRUE,
			'editable'			=> TRUE,
			//'trashable'			=> TRUE,
			'deletable'		=> TRUE,
			
			//'del_col'			=> FALSE
			//'trash_col'		=> FALSE
			
			//'where'			=> '1'
			//'limit'			=> 20
			//'orderby'			=> 'id'
		);
		parent::__construct('users', $db_init, 'admin_form');
		
		$this->wb_db->set_restriction('username!=""');
	}
	
	
	/**
	 * User login
	 * 
	 * @param $role string
	 * @return void
	 */
	public function login($role='')
	{
		$form = $this->input->post();
		
		if ($this->auth->logged_in($role))
		{
			//return to page where login was called
			$url = $this->session->get("requested_url");
			if ($url) $this->session->delete("requested_url");
			else $url = Kohana::config('routes._default');
			
			url::redirect($url); 
		}
		elseif ($form)
		{
			if ($this->logged_in)
			{
				$this->user_messages->add(Kohana::lang('login.no_access'),'error');
			}
			elseif ($this->session->get("requested_url"))
			{
				$this->user_messages->add(Kohana::lang('login.please_login'), 'error');
			}
		}
		
		if ($form)
		{
			$history = new History_Model();
			$history->log_login($form['username'], $this->input->ip_address());
			if ($history->is_bruteforced($form['username']))
			{
				$this->user_messages->add(Kohana::lang('login.bruteforce'), 'error');
			}
			else
			{
				// Load the user
				$user = ORM::factory('user', $form['username']);
				// orm user object or $form['username'] could be used
				$this->auth->login($form['username'], $form['password']);
				
				if ($this->auth->logged_in())
				{
					$this->_lang_config($user->language==1 ?  'hu_HU' : 'en_US');
					/*
					$last_login = $user->last_login;
					$last_login = empty($last_login) ? Kohana::lang('main.first_login') : date(Kohana::lang('main.tf_php'), $last_login);
					$this->session->set('last_login', $last_login);*/
				}
				else
				{
					$this->user_messages->add(Kohana::lang('login.login_failed'), 'error');
				}
			}
			
			//if (rand(0,1000)==500) $history->upkeep();
			
			url::redirect('admin/login'); 
		}
		
		$this->subtitle = Kohana::lang('login.subtitle');
		
		$this->template->main[] = new View(Kohana::config('admin.template').'/moduls/login_form');
	}
	
	/**
	 * Log out the current user
	 * 
	 * @return void
	 */
	function logout()
	{
		$this->session->destroy();
		$this->auth->logout();
		url::redirect('');
	}
}

// End of Admin_Controller